<template>
  <div class="edit-msg" v-if="designerInfo">
    <Scroll class="scroll-msg">
      <div class="scroll-inner">
        <div class="avatar">
          <van-uploader :max-count="1" v-model="fileList" :after-read="afterRead">
            <van-image round width="1.6rem" height="1.6rem" :src="ruleForm.avatar" />
          </van-uploader>
        </div>
        <div class="edit-txt">
          <van-field required label="姓名" placeholder="请输入您的姓名" v-model="viewForm.name" />
          <van-field
            required
            label="从业年限"
            readonly
            placeholder="请选择"
            v-model="ruleForm.workAge"
            @click="showYear = true"
          >
            <template slot="extra">
              <span class="icon_select">
                <span style="margin-right: 0.1rem" v-if="ageIndex < 9">年</span>
                <i></i>
              </span>
            </template>
          </van-field>
          <van-field
            required
            label="擅长风格"
            readonly
            placeholder="请选择"
            v-model="viewForm.styles"
            @click="showGoodAt = true"
          >
            <template slot="extra">
              <span class="icon_select">
                <i></i>
              </span>
            </template>
          </van-field>
          <van-field
            required
            label="设计收费"
            readonly
            placeholder="请选择"
            v-model="viewForm.rate"
            @click="showFee = true"
          >
            <template slot="extra">
              <span class="icon_select">
                元/平米
                <i></i>
              </span>
            </template>
          </van-field>
          <van-field required label="公司名称" placeholder="请输入" v-model="viewForm.companyName" />
          <van-field
            required
            label="设计类型"
            readonly
            placeholder="请选择"
            v-model="viewForm.form"
            @click="showType = true"
          >
            <template slot="extra">
              <span class="icon_select">
                <i></i>
              </span>
            </template>
          </van-field>
          <van-field label="公司电话" placeholder="请输入" v-model="viewForm.companyTel" />
          <van-field type="digit" label="手机号码" placeholder="请输入" v-model="viewForm.phone">
            <template slot="extra">
              <span @click="getCodeClick" v-if="showGetCode">{{ codeTxt }}</span>
              <span v-else style="position:relative; left: -0.4rem">{{time}}s</span>
            </template>
          </van-field>
          <van-field label="验证码" placeholder="请输入" v-model="ruleForm.captcha" />
        </div>
        <div class="btn">
          <my-button name="确定" @btnClick="submit" />
        </div>
      </div>
    </Scroll>
    <van-popup v-model="showYear" closeable position="bottom" class="popup-year">
      <div class="title">请选择从业年限</div>
      <div class="picker-box">
        <van-picker
          :columns="config.work_age"
          @change="hanldeYearChange"
          value-key="name"
          :default-index="ageIndex"
        />
        <my-button name="确定" @btnClick="yearSelected" />
      </div>
    </van-popup>
    <van-popup v-model="showGoodAt" closeable position="bottom" class="popup-gootAt">
      <div class="title">请选择擅长风格</div>
      <div class="picker-box">
        <div class="goodAt-List">
          <ul>
            <li
              v-for="(item, index) of config.styles"
              :key="index"
              :class="{'active': item.is_select}"
              @click="itemFeeClick(item)"
            >{{ item.name }}</li>
          </ul>
        </div>
        <my-button name="确定" @btnClick="stylesSelected" />
      </div>
    </van-popup>
    <van-popup v-model="showFee" closeable position="bottom" class="popup-fee">
      <div class="title">请选择收费标准</div>
      <div class="picker-box">
        <van-picker
          :columns="config.rate"
          @change="hanldeRateChange"
          value-key="name"
          :default-index="rateIndex"
        />
        <my-button name="确定" @btnClick="rateSelected" />
      </div>
    </van-popup>
    <van-popup v-model="showType" closeable position="bottom" class="popup-type">
      <div class="title">请选择设计类型</div>
      <div class="picker-box">
        <van-picker :columns="columnsType" @change="hanldeFormChange" value-key="name" />
        <my-button name="保 存" @btnClick="formSelected" />
      </div>
    </van-popup>
  </div>
</template>
<script>
import Scroll from '@/components/scroll/scroll'
import { designerInfoEdit, upload, getCaptcha } from '@/api/my'
import EditMsg from '@/views/my/mixins/edit-msg'
const ERR_OK = 200
const constantTime = 60
export default {
  components: {
    Scroll
  },
  mixins: [EditMsg],
  data () {
    return {
      ageIndex: 0,
      rateIndex: 0,
      fileList: [],
      showGetCode: true,
      time: constantTime,
      timer: null,
      codeTxt: '获取验证码',
      showYear: false,
      showGoodAt: false,
      showFee: false,
      showType: false,
      columnsType: [
        { id: 1, name: '整装' },
        { id: 2, name: '软装' }
      ],
      viewForm: {
        name: '',
        workAge: '',
        rate: '',
        styles: '',
        companyName: '',
        form: '',
        companyTel: '',
        phone: ''
      },
      ruleForm: {
        name: '',
        workAge: '',
        rate: '',
        styles: '',
        avatar: '',
        companyName: '',
        form: '',
        companyTel: '',
        phone: '',
        captcha: ''
      },
      workAge: [{ name: '1', id: 1 }],
      rate: [{ name: '300以下', id: 1 }],
      form: [{ name: '整装', id: 1 }],
      styles: []
    }
  },
  watch: {
    time (newVal) {
      if (newVal <= 0) {
        this.timer && clearInterval(this.timer)
        this.showGetCode = true
        this.codeTxt = '重新获取'
        this.time = constantTime
      }
    },
    designerInfo: {
      handler (newVal) {
        this.ruleForm.avatar = newVal.avatar
        this.ruleForm.name = newVal.name
        this.viewForm.name = newVal.name
        this.ruleForm.workAge = newVal.work_age
        this.ageIndex = parseInt(newVal.work_age) - 1
        this.viewForm.styles =
          newVal.styles.length > 1 ? newVal.styles.join(',') : newVal.styles[0]
        const arr = []
        if (newVal.styles instanceof Array) {
          newVal.styles.forEach(name => {
            arr.push(this.myFindIndexByName(name, this.config.styles).id)
            this.styles.push({
              id: this.myFindIndexByName(name, this.config.styles).id,
              is_select: true,
              name
            })
          })
        }

        this.ruleForm.styles = arr.join(',')
        if (newVal.rates) {
          this.ruleForm.rate = this.myFindIndexByName(
            newVal.rates,
            this.config.rate
          ).id
          this.rateIndex = this.myFindIndexByName(
            newVal.rates,
            this.config.rate
          ).$index
        }

        this.viewForm.rate = newVal.rates
        this.ruleForm.companyName = newVal.company_name
        this.viewForm.companyName = newVal.company_name
        if (newVal.form) {
          this.viewForm.form = this.myFindIndexById(
            newVal.form,
            this.columnsType
          ).name
        }
        this.ruleForm.form = newVal.form
        this.ruleForm.phone = newVal.phone
        this.viewForm.phone = newVal.phone
        this.ruleForm.companyTel = newVal.company_tel
        this.viewForm.companyTel = newVal.company_tel
      }
    }
  },
  destroyed () {
    this.timer && clearInterval(this.timer)
  },
  beforeRouteLeave (to, from, next) {
    // ...
    this.$emit('success')
    next()
  },
  methods: {
    myFindIndexByName (name, configArr) {
      const fIndex = configArr.findIndex((item, index) => {
        return item.name === name
      })
      configArr[fIndex].is_select = true
      if (fIndex >= 0) {
        configArr[fIndex].$index = fIndex
        return configArr[fIndex]
      }
    },
    myFindIndexById (id, configArr) {
      const fIndex = configArr.findIndex((item, index) => {
        return item.id === parseInt(id)
      })
      if (fIndex >= 0) {
        return configArr[fIndex]
      }
    },
    submit () {
      this.ruleForm.name = this.viewForm.name
      this.ruleForm.companyName = this.viewForm.companyName
      this.ruleForm.companyTel = this.viewForm.companyTel
      this.ruleForm.phone = this.viewForm.phone
      this._designerInfoEdit(this.ruleForm).then(() => {
        this.$toast('编辑资料成功~')
        this.$emit('success')
        this.$router.go(-1)
      })
    },
    afterRead (file) {
      const formData = new FormData()
      formData.append('photo', file.file)
      this._upload(formData).then(res => {
        this.ruleForm.avatar = res.data.photo
      })
    },
    stylesSelected () {
      const arr = []
      const arrName = []
      this.styles.forEach(item => {
        arr.push(item.id)
        arrName.push(item.name)
      })
      this.ruleForm.styles = arr.join(',')
      this.viewForm.styles = arrName.join(',')
      this.showGoodAt = false
    },
    formSelected () {
      this.ruleForm.form = this.form[0].id
      this.viewForm.form = this.form[0].name
      this.showType = false
    },
    yearSelected () {
      this.ruleForm.workAge = this.workAge[0].id
      this.viewForm.workAge = this.workAge[0].name
      this.showYear = false
    },
    rateSelected () {
      this.ruleForm.rate = this.rate[0].id
      this.viewForm.rate = this.rate[0].name
      this.showFee = false
    },
    itemFeeClick (item) {
      console.log(item)
      item.is_select = !item.is_select
      if (!item.is_select) {
        const fIndex = this.styles.findIndex(pItem => {
          return pItem.id === item.id
        })
        if (fIndex >= 0) {
          this.styles.splice(fIndex, 1)
        }
      } else {
        this.styles.push(item)
      }
    },
    hanldeYearChange (ref) {
      this.workAge = ref.getValues()
    },
    hanldeRateChange (ref) {
      this.rate = ref.getValues()
    },
    hanldeFormChange (ref) {
      this.form = ref.getValues()
    },
    getCodeClick () {
      if (this.showGetCode) {
        if (!this.viewForm.phone) {
          this.$toast('手机号码不能为空')
          return
        }
        this._getCaptcha(this.viewForm.phone).then(res => {
          if (res.code === ERR_OK) {
            this.showGetCode = false
            this.timer = setInterval(() => {
              this.time -= 1
            }, 1000)
          }
        })
      }
    },
    _designerInfoEdit ({
      name,
      rate,
      styles,
      avatar,
      workAge,
      companyName,
      form,
      companyTel,
      phone,
      captcha
    }) {
      return designerInfoEdit({
        name,
        rate,
        styles,
        avatar,
        workAge,
        companyName,
        form,
        companyTel,
        phone,
        captcha
      })
        .then(res => {
          if (res.code === ERR_OK) {
            return Promise.resolve(res)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },

    _upload (photo) {
      return upload(photo)
        .then(res => {
          if (res.code === ERR_OK) {
            return Promise.resolve(res)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    _getCaptcha (phone) {
      return getCaptcha(phone)
        .then(res => {
          if (res.code === ERR_OK) {
            this.$toast('验证码发送成功~')
            return Promise.resolve(res)
          }
        })
        .catch(err => {
          this.$toast(err.data.message)
          this.showGetCode = true
          this.time = constantTime
          this.timer && clearInterval(this.timer)
          console.log(err)
        })
    }
  }
}
</script>
<style lang="scss" scoped>
.edit-msg {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 9;
  background: #fff;
  touch-action: none;

  padding: 1.02rem 1.12rem 0.92rem 1.12rem;
  box-sizing: border-box;
  .scroll-msg {
    width: 100%;
    height: 100%;

    .scroll-inner {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
  .edit-txt {
    margin-top: 1rem;
    .icon_select {
      padding: 0 0.1rem;
      i {
        display: inline-block;
        width: 0.12rem;
        height: 0.21rem;
        background: url("../../../assets/images/_1.png") no-repeat;
        background-size: cover;
        vertical-align: baseline;
      }
    }
    .van-cell {
      padding-left: 0;
      padding-right: 0;
      padding: 15px 0;
      &::after {
        left: 0;
      }
      &::before {
        left: -10px;
        color: #000;
      }
    }
  }
  .btn {
    width: 100%;
    font-size: 0;
    margin-top: 0.78rem;
  }
  .popup-year,
  .popup-gootAt,
  .popup-fee,
  .popup-type {
    .title {
      font-size: 0.36rem;
      font-family: PingFang SC;
      font-weight: 500;
      color: rgba(0, 4, 0, 1);
      line-height: 0.42rem;
      text-align: center;
      padding: 0.3rem;
    }
    .picker-box {
      width: 100%;
      padding: 0.52rem 1.12rem;
      box-sizing: border-box;
    }
  }
  .popup-gootAt {
    .picker-box {
      padding: 0.52rem 0.8rem;
      .goodAt-List {
        ul {
          display: flex;
          justify-content: center;
          flex-wrap: wrap;
          li {
            padding: 0.1rem 0.2rem;
            background: rgba(255, 255, 255, 1);
            border: 1px solid rgba(153, 153, 153, 1);
            margin-right: 0.3rem;
            margin-bottom: 0.42rem;
            font-size: 0.28rem;
            font-family: PingFang SC;
            font-weight: 500;
            color: rgba(0, 4, 0, 1);
            line-height: 0.42rem;
            &.active {
              border: 1px solid #000400;
              background: url("../../../assets/images/icon_xuanzhong.png")
                no-repeat;
              background-position: right bottom;
              background-size: 0.3rem 0.2rem;
            }
          }
        }
      }
    }
  }
}
</style>
